#coding=UTF-8
'''
 @date    : 2022/08/12
 @Author  : Donkey
 @Email   : lyzong8023@.com
 # 编译： pyinstaller -F iBoxNotice.py
'''
import json
from datetime import datetime
import time
from requests.exceptions import RequestException
import requests
from selenium import webdriver
from time import sleep
from selenium.webdriver.chrome.options import Options
from selenium.webdriver import Chrome
from selenium.webdriver import ChromeOptions

import re


Maxnotice = nowmax = 331  # 定义当前最大公告
flag=0 # 统计公告数量
def sendDing(url,txt):
    try:
        #正式环境
        webHook = 'https://oapi.dingtalk.com/robot/send?access_token=xxxxxxxxx'
        
        headers = {
            "Content-Type": "application/json;charset=utf-8"
        }
        json_text = {
            "msgtype": "text",
            "text": {
                "content": "欢迎VX关注【IT散记】！"+'\n'+"点击查看公告详情："+url+'\n'+txt
            },
            "at": {
                "atMobiles": [
                    ""
                ],
                "isAtAll": True
            }
        }
        response=requests.post(webHook, json.dumps(json_text), headers=headers)
        if response.status_code == 200:
           print("钉钉推送成功，今日推送数量：",flag)

    except RequestException:
        return None



def timer(n):
    while True:
        print(datetime.now().strftime("%Y-%m-%d %H:%M:%S"))

        tete()
        time.sleep(n)

def test():

    # 添加请求头
    headers = {
        "User-Agent": "PostmanRuntime/7.29.0",
        "Accept": "*/*",
        "Accept-Encoding": "gzip, deflate, br",
        "Connection": "keep-alive"
    }
    res = requests.get("https://api-h5.ibox.art/nft-mall-web/v1.2/nft/product/getCommonNoticeList?page=1&pageSize=20",
                       headers=headers)
    datas = res.json()
    max = datas["data"]["list"][0]["id"]
    for i in range(20):
        if (max < datas["data"]["list"][i]["id"]):
            max = datas["data"]["list"][i]["id"]
            maxIndex = i
    noticeId=max
    noticeName=datas["data"]["list"][maxIndex]["noticeName"]
    noticeTime=datas["data"]["list"][maxIndex]["noticeTime"]
    print(noticeTime)
    sendDing(noticeName)

#@with_goto     #必须有
def tete():
    global Maxnotice, nowmax
    global flag,maxela,maxurl
   # label.begin  # 标识跳转并开始执行的地方
    try:
        chrome_options = Options()
        options = ChromeOptions()
        options.add_experimental_option('excludeSwitches', ['enable-automation'])
        options.add_experimental_option('useAutomationExtension', False)
        chrome_options.add_argument("--headless")
        chrome_options.add_argument('--no-sandbox')
        chrome_options.add_argument('--disable-gpu')
        chrome_options.add_argument('--disable-dev-shm-usage')
        browser = Chrome(
          executable_path=r"/root/driver/chromedriver",options=chrome_options
        )
        msnow= int(round(time.time() * 1000))
        url = 'https://notice.ibox.art/html/notice/notice.html?'+str(msnow)

        browser.get(url)
        sleep(5)
       # print(browser.page_source)
        el = browser.find_elements_by_xpath('//*[@class="content-list_5266e0"]')
        for p in el:
            try:
                item = p.find_elements_by_class_name("list-item_3176d9")

                dt=item[0].find_element_by_class_name("time_18d71f").text
                # item[0].click()
                # sleep(3)
                # txt = browser.find_element_by_xpath('//*[@class="page-notice-detail"]').text
                # print("timne:",dt)
                # 转换成时间数组
                timeArray = time.strptime(dt, "%Y-%m-%d %H:%M")
                # 转换成时间戳
                timestamp = int(time.mktime(timeArray))
                # print(timestamp)

            except:
                pass
            else:
                 if nowmax < timestamp:
                    nowmax = timestamp
                    maxela = item[0]

        #print("new Notice:",maxela.text)
    except:
       # browser.quit()
        print("encountered an exception!")

       # goto.begin  # 在有跳转标识的地方开始执行

    else:
        if flag==0:
            flag=flag+1
            Maxnotice = nowmax
            print("程序启动成功！当前notice:",nowmax)
        else:
            if nowmax>Maxnotice:
                #print("success! start query details! id="+num[0])
                Maxnotice = nowmax
                biaoti=maxela.text
                #开始获取详情
                try:
                    maxela.click()
                    sleep(5)
                    browser.switch_to.window(browser.window_handles[-1])
                    txt=browser.find_elements_by_xpath('//*[@class="page-notice-detail_b4ea9e"]')[0].text
                    maxurl=browser.current_url
                except:
                    print("detail encountered an exception!")
                    sendDing(maxurl,biaoti)
                else:
                    sendDing(maxurl, txt)
                browser.quit()
                flag=flag+1
            else:
                browser.quit()
                print("本次未检测到更新！")

def main():

    timer(7)



if __name__ == '__main__':
     main()





